from websocket.msghandler import MsgContext, MessageType


class MultiTaskIndicators:
    @classmethod
    def handle(cls, message):
        indicator_data = message['indicator_data']
        statistical_type = message['statistical_type']
        indicator_name = indicator_data['name']
        problem_datas_length = len(MsgContext.multiple_populations)
        algorithms_datas_length = len(MsgContext.multiple_populations[0])
        run_size = len(MsgContext.multiple_populations[0][0])
        is_exist = indicator_name in MsgContext.multiple_indicators
        indicator_values = None
        if is_exist:
            indicator_values = MsgContext.multiple_indicators[indicator_name]
        for problem_index in range(problem_datas_length):
            for algorithm_index in range(algorithms_datas_length):
                for nth_run in range(run_size):
                    if indicator_name == MsgContext.num_of_run:
                        MsgContext.num_of_run_return(algorithm_index, problem_index)
                    else:
                        if (not is_exist) or (
                                is_exist and indicator_values[problem_index][algorithm_index][nth_run] < 0):
                            intermediate_pops = MsgContext.multiple_populations[problem_index][algorithm_index][
                                nth_run]
                            MsgContext.calc_indicator(indicator_data, intermediate_pops, problem_index, algorithm_index,
                                                      nth_run)
                            MsgContext.save_indicator(algorithm_index, intermediate_pops,
                                                      nth_run, problem_index)
                        MsgContext.return_res(problem_index, algorithm_index, indicator_data)
        # 计算统计检验结果
        if indicator_name != MsgContext.num_of_run:
            MsgContext.statistical_result(algorithms_datas_length, problem_datas_length, indicator_data,
                                          statistical_type)
        MsgContext.task_complete_return(MessageType.MULTI_TASK_COMPLETED)
